package pl.edu.agh.mbc.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

import org.apache.log4j.Logger;

import pl.agh.mbc.server.MBCPacket;
import pl.edu.agh.mbc.database.dao.commons.DaoControll;

/**
 * 
 * @author wkedzior
 * 
 */
public class ServerWorker implements Runnable {
	private static final Logger LOG = Logger.getLogger(ServerWorker.class);
	private Socket socket;
	private DaoControll dbCommons;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	private ServerHandler handler;

	public ServerWorker(Socket socket, DaoControll service)
			throws IOException {
		this.dbCommons = service;
		this.handler = new ServerHandler(service);
		initialize(socket);
	}

	private void initialize(Socket socket) throws SocketException, IOException {
		this.socket = socket;
		this.socket.setKeepAlive(true);
		this.ois = new ObjectInputStream(socket.getInputStream());
		this.oos = new ObjectOutputStream(socket.getOutputStream());
	}

	private void doAction() {
		try{
			Object o;
			/**
			 * Bardzo prosty schemat...mozna by tutaj podlubac jak zostanie czas.
			 */
				while (( o = ois.readObject()) != null) {
						System.out.println(o.toString());
						if (o!= null && o instanceof MBCPacket){
							// tutaj nastapi odelegowanie operacji, na razie umieszczm w tym bloku, bo nie mam czasu
							MBCPacket packet = (MBCPacket)o;
								oos.writeObject(handler.recognizeAndReturn(packet));
								oos.flush();
							}else{
								LOG.error("Unrecognized object!!");
								oos.flush();
							}		
						}
						
		}catch(Exception ex){
			LOG.error("Stopping server thread for client " + socket.getInetAddress(), ex);
		}
	}

	public void run() {
			doAction();
	}	
}
